package ccnu.agile.bean.response;

import ccnu.agile.enums.PrivError;
import ccnu.agile.enums.PubError;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * @Description: 通用返回体类
 * @Author: JreamY
 * @Date: 2021/5/17
 **/
@Getter
@Setter
@ToString
public class Response implements Serializable {

    protected final static Integer SUCCESS = 0;
    protected final static Integer FAILURE = 1;

    /**
     * 0成功，1失败
     */
    private Integer resultCode;
    /**
     * 对外错误码
     */
    private String errorCode;
    /**
     * 对内错误码
     */
    private String privCode;
    /**
     * 错误描述
     */
    private String errorDesc;

    public static Response newSuccess() {
        Response response = new Response();
        return response.setSuccess();
    }

    public static Response newFailure() {
        Response response = new Response();
        return response.setFailure();
    }

    public static Response newFailure(PubError error) {
        return newFailure().setError(error);
    }

    public static Response newFailure(String errorCode, String errorDesc, String privCode) {

        Response response = newFailure();
        response.setErrorCode(errorCode);
        response.setErrorDesc(errorDesc);
        response.setPrivCode(privCode);
        return response;
    }

    public static Response newFailure(PubError error, String privCode) {
        Response response = newFailure(error);
        response.setPrivCode(privCode);
        return response;
    }

    public static Response newFailure(PubError error, PrivError privError, boolean changeDesc) {
        Response response = newFailure(error, privError.getErrorCode());
        if (changeDesc) {
            response.setErrorDesc(privError.getErrorDesc());
        }
        return response;
    }

    public Response setSuccess() {
        this.resultCode = SUCCESS;
        return this;
    }

    public Response setFailure() {
        this.resultCode = FAILURE;
        return this;
    }

    public Response setFailure(PubError error, PrivError privError) {
        return this.setFailure(error, privError, false);
    }

    public Response setFailure(PubError error, PrivError privError, boolean changeDesc) {
        this.setFailure().setErrorCode(error.getErrorCode());
        this.setErrorDesc(changeDesc ? privError.getErrorDesc() : error.getErrorDesc());
        this.setPrivCode(privError.getErrorCode());
        return this;
    }

    public Response setError(PubError error) {
        this.errorCode = error.getErrorCode();
        this.errorDesc = error.getErrorDesc();
        return this;
    }

    public boolean statusOk() {
        return SUCCESS.equals(this.resultCode);
    }
}
